package net.wanho.shop.service.impl;

import lombok.RequiredArgsConstructor;
import net.wanho.shop.common.UserConstant;
import net.wanho.shop.mapper.PermissionMapper;
import net.wanho.shop.mapper.RoleMapper;
import net.wanho.shop.po.Permission;
import net.wanho.shop.po.Role;
import net.wanho.shop.service.MenuService;
import net.wanho.shop.util.CurrentUtil;
import net.wanho.shop.vo.MenuVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class MenuServiceImpl implements MenuService {

    private final RoleMapper roleMapper;
    private final PermissionMapper permissionMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override

    public List<MenuVo> findMenus() {
        // 从Redis中获取菜单
        List<MenuVo> menus = (List<MenuVo>) redisTemplate.opsForValue()
                .get(UserConstant.MENU_PREFIX + CurrentUtil.getId());
        // 如果为空，则从数据库中获取
        if (!CollectionUtils.isEmpty(menus)) {
            return menus;
        }


        // 获取当前用户所有的权限
        Role role = roleMapper.selectByUserId(CurrentUtil.getId());
        String[] ids = role.getPsIds().split(",");
        List<Permission> permissions = permissionMapper.selectBatch(ids);


        // 获取一级菜单
        menus = permissions.stream()
                .filter(item -> item.getPsPid() == 0)
                .map(item -> {
                    // 将Permission转换为MenuVo
                    MenuVo menuVo = wrapper(item);
                    // 获取二级菜单
                    List<MenuVo> children = permissions.stream()
                            .filter(subItem -> subItem.getPsPid().equals(item.getPsId()))
                            .map(this::wrapper)
                            .collect(Collectors.toList());
                    menuVo.setChildren(children);
                    return menuVo;
                })
                .collect(Collectors.toList());

        // 将菜单存入Redis
        redisTemplate.opsForValue().set(UserConstant.MENU_PREFIX + CurrentUtil.getId(), menus,
                UserConstant.MENU_EXPIRE, UserConstant.MENU_UNIT);

        return menus;
    }


    // 将Permission转换为MenuVo
    private MenuVo wrapper(Permission item) {
        MenuVo menuVo = new MenuVo();
        menuVo.setId(item.getPsId());
        menuVo.setAuthName(item.getPsName());
        menuVo.setPath(item.getPsApiPath());
        menuVo.setOrder(item.getPsApiOrder());
        return menuVo;
    }
}